package com.droidclaimsurveyor.helper.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class FileHandle {
	private static String DROID_CLAIM = "droidclaim";
	private static File IMAGE_DIRECTORY = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),DROID_CLAIM);

	public static String writeImage(Bitmap bitmap) {
		String filename = "";

		try {
			//Date date = new Date();
			//SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			//filename = sdf.format(date) + ".jpg";
			filename = FileHandle.getUnigueImageFileName("");
			String destFilePath = FileHandle.getFilePath(filename);

			File file = new File(destFilePath);
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			final int BUFFER_SIZE = 1024 * 8;
			final BufferedOutputStream bos = new BufferedOutputStream(fos,
					BUFFER_SIZE);
			bitmap.compress(CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
			fos.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return filename;
	}
	
	public static Bitmap getImage(String filename) {
		Bitmap bitmap = null;
		try {
			String filePath = FileHandle.getFilePath(filename);
			File imgFile = new File(filePath);
			if (!imgFile.exists()) {
				throw new Exception("empty filename");
			}

			bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return bitmap;
	}
	
	public static String getUnigueImageFileName(String identifyStr){
		Date date = new Date();
		
		String filename = "";
		if(!identifyStr.isEmpty()){
			filename = identifyStr + "_";
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		filename += sdf.format(date);
		filename += ".jpg";
		
		return filename;
	}
	
	public static String getFilePath(String fileName){
		return getFolderPath() + File.separator + fileName;
	}
	
	public static String getFolderPath(){
		if (!IMAGE_DIRECTORY.exists()) {
            if (!IMAGE_DIRECTORY.mkdirs()) {
                Log.d("Droidclaim", "failed to create directory");
                return null;
            }
        }
		
		String path = IMAGE_DIRECTORY.getPath();
		return path;
	}
}
